<template>
  <!-- 个人中心 -->
  <div class="app-container">
    <el-row :gutter="20" class="paddingT20">
      <el-col :span="6">
        <el-card shadow="never">
          <div slot="header" class="header-title">
            <el-row>
              <el-col :span="12">
                <span>个人信息</span>
              </el-col>
              <el-col :span="12" class="logout">
                <span v-if="loginType === '1'" @click="cancellation(personnelLogout)">用户注销</span>
                <span v-if="userType === '01'" @click="cancellation(enterpriseLogout)">企业注销</span>
              </el-col>
            </el-row>
          </div>
          <el-row type="flex" justify="center">
            <!-- 头像上传功能 -->
            <uploadAvatar :avatar-files="appFiles" />
          </el-row>
          <el-divider />
          <div class="baseinfo">
            <!--用户信息-->
            <div>
              <template v-for="(item,index) in profileInfo">
                <el-row :key="index" type="flex" justify="space-between">
                  <span class="titleSpan">
                    <i :class="item.icon" />
                    {{ item.title }}
                  </span>
                  <span class="contentSpan">{{ item.content }}</span>
                </el-row>
                <el-divider :key="index" class="dividerClass" />
              </template>
            </div>
            <!--员工信息-->
            <div v-if="loginType && loginType !== '1'">
              <template v-for="(item,index) in EnterprisesFilter">
                <el-row :key="index" type="flex" justify="space-between">
                  <span class="titleSpan">
                    <i :class="item.icon" />
                    {{ item.title }}
                  </span>
                  <span class="contentSpan">{{ item.content }}
                    <span v-if="item.content==='在职'" class="quit" @click="handleQuit">离职</span>
                  </span>
                </el-row>
                <el-divider :key="index" class="dividerClass" />
              </template>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card shadow="never">
          <div slot="header" class="header-title">
            <span>基本资料</span>
          </div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本资料" name="baseInfo">
              <baseInfo :wx-url="wxUrl" :login-form-data="loginFormData" />
            </el-tab-pane>
            <el-tab-pane label="修改密码" name="updatePassword">
              <updatePassword />
            </el-tab-pane>
            <!-- 企业管理 -->
            <el-tab-pane v-if="loginType === '1'" label="企业管理" name="fourth">
              <enterpriseMange
                ref="enterpriseMange"
                :type-options="typeOptions"
                :table-data="tableData"
              />
            </el-tab-pane>
            <!-- 我的证书 -->
            <el-tab-pane v-if="loginType !== '2'" label="人员证书" name="third">
              <certificateList :add-cert-list="addCertList" :cert-list.sync="userCertificates" edit="1" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getWxUid } from '@/api/system/profile'
import { changeCertificate } from '@/api/register'
import { updateQuitStatus } from '@/api/system/user'
import { mapState } from 'vuex'
import { listNoPermission } from '@/api/superviseBaseInfo/typeManage/organizationType'
// 接口功能引入
import { listCurrentUser } from '@/api/system/profile'
// 获取登录类型
import { getLoginType } from '@/utils/auth'
// 基本信息
import baseInfo from './components/baseInfo'
// 更新密码
import updatePassword from './components/updatePassword'
// 企业管理
import enterpriseMange from './components/enterpriseMange'
// 上传头像
import uploadAvatar from './components/uploadAvatar'
// 证件列表
import certificateList from '@/components/certificateList'
// 注销
import { enterpriseLogout, personnelLogout } from '@/api/register'

export default {
  name: 'Profile',
  components: {
    baseInfo,
    updatePassword,
    enterpriseMange,
    certificateList,
    uploadAvatar
  },
  data() {
    return {
      wxUrl: '',
      enterpriseLogout,
      personnelLogout,
      // 个人信息title
      profileInfo: [
        {
          title: '用户名称',
          icon: 'el-icon-user',
          content: ''
        },
        {
          title: '手机号码',
          icon: 'el-icon-mobile-phone',
          content: ''
        },
        {
          title: '用户邮箱',
          icon: 'el-icon-message',
          content: ''
        },
        {
          title: '创建日期',
          icon: 'el-icon-date',
          content: ''
        }
      ],
      // 员工信息
      EnterprisesInfo: [
        {
          title: '所属部门',
          icon: 'el-icon-set-up',
          content: ''
        },
        {
          title: '所属角色',
          icon: 'el-icon-s-custom',
          content: ''
        },
        {
          title: '所属企业',
          icon: 'el-icon-set-up',
          enterprise: '',
          content: ''
        },
        {
          title: '员工状态',
          icon: 'el-icon-bangzhu',
          content: '在职'
        }
      ],
      // 标签页所处标签项
      activeName: 'baseInfo',
      // 企业列表
      tableData: [],
      addCertList: [], // 新增选择的证书
      userCertificates: [], // 人员证书
      loginFormData: {
        loginName: '',
        userName: '',
        phonenumber: '',
        email: '',
        avatarList: ''
      },
      sysUserAccount: '',
      sysUser: '',
      appFiles: '',
      // 接收接口返回的数据
      currentUserData: {},
      typeOptions: [] // 企业类型
    }
  },
  computed: {
    ...mapState({
      userId: state => state.user.userInfo.userId,
      sysAccount: state => state.user.sysAccount,
      userType: state => state.user.userType,
      loginType: state => state.user.loginType
    }),
    EnterprisesFilter() {
      return this.EnterprisesInfo.filter(item => {
        if (item.title === '员工状态') {
          return this.sysUserAccount && this.sysUser
        } else {
          return true
        }
      })
    }
  },
  mounted() {
    this.listCurrentUser()
    this.getSupperType()
    this.getSysAccountData()
  },
  methods: {
    // 人员离职
    handleQuit() {
      this.$prompt('确认要离职吗？,请输入登录密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: '密码长度不正确!'
      }).then(({ value }) => {
        updateQuitStatus({ status: 1, userId: this.userId, password: value }).then(res => {
          if (res.data) {
            this.msgSuccess('离职成功!')
            this.$store.dispatch('user/logout').then(() => {
              location.href = '/login'
            })
          }
        })
      }).catch(() => {
        this.msgWarning('已取消')
      })
    },
    async getSysAccountData() {
      if (getLoginType() !== '1') return
      const wxUrl = await getWxUid({ wxUrl, userId: this.userId })
      wxUrl && (this.wxUrl = wxUrl)
      const { phone: phonenumber, email, surveyType, name: userName, sex, createTime, avatar, userCertificates } = this.sysAccount
      this.loginFormData = { phonenumber, userName, email, sex }
      this.profileInfo[0].content = userName
      this.profileInfo[1].content = phonenumber
      this.profileInfo[2].content = email
      this.profileInfo[3].content = createTime
      this.userCertificates = userCertificates
      if (avatar) {
        this.appFiles = avatar
      }
      this.getCertList(surveyType)
    },
    async getCertList(typeNum) {
      const { data } = await changeCertificate({ typeFlag: '0', typeNum })
      this.addCertList = data
    },
    async getSupperType() {
      const query = { typeVal: 1 }
      const { data: { rows }} = await listNoPermission(query)
      this.typeOptions = rows
    },
    // 获取当前用户信息
    async listCurrentUser() {
      if (getLoginType() === '1') return
      const { data: { sysUser, sysUserAccount }} = await listCurrentUser()
      let loginFormData = ''
      if (getLoginType() === '0') {
        loginFormData = sysUserAccount
        const wxUrl = await getWxUid({ loginType: getLoginType(), id: sysUserAccount.id })
        wxUrl && (this.wxUrl = wxUrl)
      } else if (getLoginType() === '2') {
        loginFormData = sysUser
        const wxUrl = await getWxUid({ loginType: getLoginType(), id: sysUser.userId })
        wxUrl && (this.wxUrl = wxUrl)
      }
      this.sysUserAccount = sysUserAccount
      this.sysUser = sysUser
      const { userName, name, phonenumber, phone, email, sex, userCertificates } = loginFormData
      const { roles, enterpriseName, createTime, sysUserType, loginName, dept, avatar } = sysUser
      if (sysUserType) {
        this.getCertList(sysUserType)
      }
      if (userCertificates) {
        this.userCertificates = userCertificates
      }
      this.profileInfo[0].content = name || userName
      this.profileInfo[1].content = phone || phonenumber
      this.profileInfo[2].content = email
      this.profileInfo[3].content = createTime
      this.EnterprisesInfo[0].content = dept.deptName
      this.EnterprisesInfo[2].content = enterpriseName
      if (roles.length > 0) {
        this.EnterprisesInfo[1].content = roles[0].roleName
      }
      this.loginFormData.loginName = loginName
      this.loginFormData.userName = name || userName
      this.loginFormData.phonenumber = phone || phonenumber
      this.loginFormData.email = email
      this.loginFormData.sex = sex
      if (avatar) {
        this.appFiles = avatar
      }
    },
    // 注销
    cancellation(requestName) {
      this.$prompt('注销账号,请输入密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        inputPattern: /^.{6,20}$/,
        inputErrorMessage: '密码长度不正确!'
      }).then(({ value }) => {
        const userId = this.loginType === '1' ? this.sysAccount.id : ''
        const data = { id: userId, status: 1, password: value }
        requestName(data).then(res => {
          if (res.code === 200) {
            this.msgSuccess('注销成功')
            this.$store.dispatch('user/logout').then(() => {
              location.href = '/login'
            })
          } else if (res.code === 202) {
            this.msgWarning(res.message)
          }
        })
      }).catch(() => {
        this.msgWarning('已取消')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.paddingT20 {
  padding-top: 20px;
}
.app-container {
  .header-title {
    font-size: 16px;
    .logout{
      text-align: right;
      span{
        color:#0a7fff;
        cursor: pointer;
        font-size: 12px;
      }
    }
  }
  .baseinfo {
    font-size: 14px;
    .titleSpan {
      display: inline-block;
      width: 95px;
      margin-right: 5px;
    }
    .contentSpan {
      text-align: right;
      display: inline-block;
      min-width: 150px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .quit {
      margin-left: 11px;
      color: #0970f7;
      cursor: pointer;
    }
  }
}
.baseinfo-form {
  width: 50%;
}
.dividerClass {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
